#!/user/bin/env python3
# -*- coding: utf-8 -*-
"""
--------------------------------------
    Author:     JiChao_Song
    Date  :     2020/12/18 12:01
    Desc  :     阿里云相关api操作
--------------------------------------
"""
import os
import time

import oss2

from config.base import ALIBABA_ACCESS_ID, ALIBABA_ACCESS_SECRET, ENDPOINT


def get_filename(filepath):
    """
    获取文件名称和文件扩展名
    :param filepath:
    :return: filename, extname
    """

    (path, file) = os.path.split(filepath)
    return os.path.splitext(os.path.split(file)[1])


class AlibabaUtils:

    def __init__(self):
        self.auth = oss2.Auth(ALIBABA_ACCESS_ID, ALIBABA_ACCESS_SECRET)

    def bucket(self):
        return oss2.Bucket(self.auth, ENDPOINT, 'jcsongyun')

    def uploadFilePath(self, filepath, putObjectName):
        """
        简单上传
        :return:
        """
        # 上传到阿里云的文件名
        with open(filepath, 'rb') as f:
            self.bucket().put_object(putObjectName, f)
            return f'http://jcsongyun.{ENDPOINT}/{putObjectName}'

    def uploadFile(self, file, putObjectName):

        self.bucket().put_object(putObjectName, file)
        return f'http://jcsongyun.{ENDPOINT}/{putObjectName}'

    def deleteFile(self, putObjectName):
        """
        删除文件
        :param putObjectName: 文件完整路径
        :return:
        """
        self.bucket().delete_object(putObjectName)


if __name__ == '__main__':
    filepath = '../../uploads/接口测试用例模板.xlsx'
    (filename, ext) = get_filename(filepath)
    putObjectName = f'flaskapi/{filename}-{int(time.time())}{ext}'
    bucket = AlibabaUtils().bucket()
    print(AlibabaUtils().uploadFilePath(filepath, putObjectName))
